﻿/***************************************
= Application Variables
-------------------------------------- */
var cDirectory = '';

/***************************************
= Thumb Img
-------------------------------------- */
function cropImg(width, height, imgName) {
    return String.format('{0}crop/{1}_{2}/{3}', Base64.decode(Domain), width, height, cDirectory + '/' + imgName);
}

function originalImg(imgName) {
    return String.format('{0}/{1}', Base64.decode(Domain), cDirectory + '/' + imgName);
}

/***************************************
= View Directories
-------------------------------------- */

// View Directories
//#region
function viewDirectories(quizType, dirName, absolute) {

    if (absolute == true)
        cDirectory = dirName;
    else
        cDirectory = cDirectory + "/" + dirName;
            
    console.log('View Directories - Get Current Director: ' + cDirectory);
    
    var totalFolders = 0;
    var totalFiles = 0;
    
    $('#listFileManager').html('');

    var html = '';
    
    html += '<div id="statsFm"></div>';
    
    html += '<div class="widget" style="margin-top: 20px">';
    html += '<div class="head"><h5 class="iFiles">Quản lý thư mục và ảnh</h5></div>';

    // build link url
    var url = '';    
    var lstUrl = cDirectory.split('/');
    if (lstUrl.length > 0) {
        
        for (var i = 0; i < lstUrl.length; i++) {
            if (i == 0) {
                url += String.format('<a>{0}<a/> / ', lstUrl[0]);
            }
            else {
                var temp = '';
                for (var j = 0; j <= i; j++) {
                    temp += String.format('{0}/', lstUrl[j]);
                }
                temp = temp.substring(0, (temp.length - 1));

                url += String.format('<a href="#" onclick="viewDirectories(\'{0}\',\'{1}\', true)">{2}<a/> / ', quizType, temp, lstUrl[i]);        
            }            
        }

        url = url.substring(0, url.length - 2);        
    }

    // Nếu là Small Size thì hiển thị nút chèn danh sách ảnh
    if (quizType == 'smallsize')
        html += '<h2 class="iFolder contentHead">/ ' + url + '<input type="button" onclick="selectFile(this, \'list\');" class="seaBtn floatright" value="Chọn ảnh cho Small Size" /></h2>';            
    else 
        html += '<h2 class="iFolder contentHead">/ ' + url + '</h2>';    
        
    html += '<div class="curves"></div>';        
    
    html += '<div id="makeDirFm"></div>';
    
        html += '<div class="pt20">';
            html += '<div class="breadCrumbHolder module">';
                html += '<div id="folderFm" class="breadCrumb module">';
                    html += '<ul>';
                    html += '<li class="firstB"><a>Home</a></li>';                        
                    html += '</ul>';
                html += '</div>';
                html += '<div style="float: right">';                    
                    html += '<a class="btn14 mr5 topDir" title="Upload" onclick="uploadHtml();"><img alt="" src="/images/icons/dark/upload.png"/></a>';
                    html += String.format('<a class="btn14 mr5 topDir" title="Refresh" onclick="viewDirectories(\'{0}\',\'{1}\', true)"><img alt="" src="/images/icons/dark/refresh.png"/></a>', quizType, cDirectory);
                    html += '<a class="btn14 mr5 topDir" title="Tạo thư mục" onclick="makeDirHtml();"><img alt="" src="/images/icons/dark/folder.png"/></a>';                    
                    html += '<a class="btn14 mr5 topDir" title="Xóa thư mục" onclick="removeDir();"><img alt="" src="/images/icons/dark/close.png"/></a>';                    
                html += '</div>';
            html += '</div>';
        html += '</div>';

        html += '<div id="filesFm"></div>';

        html += '<div class="fix"></div>';
    html += '</div>';

    $('#listFileManager').html(html);

    $.ajax({
        url: '/Handlers/StorageHandler.ashx',
        data: { 'command': 'viewdirectories', 'dirname': cDirectory },
        dataType: 'json',
        async: false,
        success: function (data) {
            // Folder
            try {
                var folders = data.directories.length;
                if (folders > 0) {
                    var fo = '';
                    for (var i = 0; i < folders; i++) {
                        fo += String.format('<li><a href="#" onclick="viewDirectories(\'{0}\',\'{1}\', false);"><strong>{1}</strong></a></li>', quizType, data.directories[i]);
                        totalFolders++;
                    }
                    $('#folderFm ul').append(fo);
                }                
            } catch (e) { }

            // Files    
            try {
                var files = data.files.length;
                if (files > 0) {
                    var fi = '';
                    fi += '<div class="pics">';
                    fi += '<ul>';

                    for (var j = 0; j < files; j++) {
                        if (quizType == 'smallsize') {
                            fi += String.format('<li><a href="#" onclick="activeFile(this, \'add\');"><img src="{0}" alt="" style="width: 102px; height: 102px" /></a>', cropImg(80, 80, data.files[j]));
                            fi += '<div class="actions">';
                            fi += String.format('<a href="#" onclick="activeFile(this, \'add\');" rel="{0}"><img src="/images/add.png" alt="" /></a>', data.files[j]);
                            fi += String.format('<a href="#" onclick="activeFile(this, \'delete\');" rel="{0}"><img src="/images/delete.png" alt="" /></a>', data.files[j]);
                            fi += '</div>';
                            fi += '</li>';
                        }
                        else {
                            fi += String.format('<li><a href="#" onclick=\'selectFile(this, \"{0}\");\' rel="{1}"><img src="{2}" alt="" style="width: 102px; height: 102px" /></a>', quizType, data.files[j], cropImg(80, 80, data.files[j]));
                            fi += '<div class="actions">';
                            fi += String.format('<a href="#" onclick="deleteFile(this);" rel="{0}"><img src="/images/delete.png" alt="" /></a>', data.files[j]);
                            fi += '</div>';
                            fi += '</li>';                                                        
                        }                                                                                                
                        totalFiles++;
                    }

                    fi += '</ul>';
                    fi += '<div class="fix"></div>';
                    fi += '<div>';

                    $('#filesFm').html(fi);
                }                
            } catch (e) { }

            // basic stats
            var stats = '';
            stats += '<div class="stats ml10">';
            stats += '<ul>';
            stats += '<li><a title="" class="count green" href="#">' + totalFolders + '</a><strong>Thư mục</strong></li>';
            stats += '<li><a title="" class="count red" href="#">' + totalFiles + '</a><strong>Ảnh</strong></li>';
            stats += '</ul>';
            stats += '<div id="messageFm" class="floatright"></div>';
            stats += '<div class="fix"></div>';
            stats += '</div>';
            $('#statsFm').html(stats);

            if (quizType == 'smallsize') {
                var message = '';
                message += '<div class="nNote nInformation hideit" style="width: 400px; margin: 0 10px 0 0">';
                message += '<p>Nhấn dấu "+" để thêm ảnh, "x" để xóa ảnh chọn cho small size.<br/>Nhấn "Chọn ảnh cho Small Size" để chèn vào đáp án.</p>';
                message += '</div>';
                message += '<div class="fix"></div>';

                $('#messageFm').html(message); // message
            }
            
        },
        error: function (result) {
            console.log('Error View Directories' + result);
        }
    });           
}
//#endregion

/***************************************
= Select File
-------------------------------------- */

// Active File
//#region
function activeFile(obj, action) {
    var li = $(obj).parents('li');    
    switch (action) {
        case 'add':
            $(li).addClass('imgFrame');
            break;
        case 'delete':
            $(li).removeClass('imgFrame');
            break;
    }
}

//#endregion

//#region

// Select File
function selectFile(obj, typeName) {
    if(typeName == 'list') // Small Size
    {
        var value = '';
        $.each($('.pics li'), function () {

            var isSelected = $(this).hasClass('imgFrame');
            if (isSelected == true) {
                var imgName = $(this).find('a:eq(1)').attr('rel');
                var imgPath = cDirectory + '/' + imgName;                
                value += imgPath + "►";
            }
        });

        console.log('List Small Size: ' + value);
                
        // set list src image to textbox
        $('#txtImageList').val(value);

        var smallSizeItem = '';
        var splitSmallSize = value.split("►");
        $(splitSmallSize).each(function (index, val) {
            if (val.toString().length > 0) {
                smallSizeItem += createSmallSize("", val.toString(), "");
            }
        });

        $('.smallsize').append(smallSizeItem);
        $('.topDir').tipsy({ fade: true, gravity: 's' });
        removeSmallSize();        
        
    }
    else {
        var imgName = $(obj).attr('rel');
        if (imgName != null && imgName.length > 0) {
            switch (typeName) {
                case 'editor':  // TinyMCE
                    var img = String.format('<img src="{0}" alt=""/>', originalImg(imgName));
                    tinyMCE.execCommand('mceInsertContent', false, img);
                    break;
                default :   // TextBox
                    $('#' + typeName).val(cDirectory + '/' + imgName);
                    break;
            }            
        }
    }

    disablePopupQuiz();
}

//#endregion

/***************************************
= Upload
-------------------------------------- */

//#region

function uploadHtml() {
    $('#popup_container').css('display', 'block');

    $('#popup_title').empty();
    $('#popup_message').empty();

    $('#popup_title').append("Tải dữ liệu lên máy chủ");

    $('#popup_message').load('/Upload.aspx');
    $('#popup_message').css({ 'overflow-y': 'auto', 'height': '300px' });
    
    //setTimeout("reloadViewDirectories();", 5000);
}
/*
function reloadViewDirectories() {
    var dt = new Date();
    var adminUserId = Base64.decode(AdminUserId);
    if (adminUserId > 0) {
        var urlFolder = String.format("files/{0}/{1}/{2}/{3}", adminUserId, dt.getFullYear(), dt.getMonth() + 1, dt.getDate());
        console.log(urlFolder);
        viewDirectories(urlFolder, true);
    }    
}
*/
//#endregion


/***************************************
= Make Dir (Html & Action)
-------------------------------------- */

//#region

function makeDirHtml() {
    var html = '';
    html += '<fieldset>';    
    
    html += '<div class="rowElem nobg">';
    html += '<label>Tên thư mục:</label>';
    html += '<div class="formRight" style="width: 78%"><input id="txtFolderName" type="text" name="inputtext"/></div>';
    html += '<div class="fix"></div>';
    html += '</div>';

    html += '<input type="button" class="seaBtn submitForm mb22" style="margin-right: 15px;" onclick="removeMakeDirHtml();" value="Đóng"/>';
    html += '<input type="button" class="seaBtn submitForm mb22" onclick="makeDir();" value="Tạo mới"/>';
    
    html += '<div class="fix"></div>';
    html += '</div>';
    
    html += '</fieldset>';
        
    $('#makeDirFm').html(html);
}

function removeMakeDirHtml() {
    $('#makeDirFm').html('');
    return false;
}

//#endregion

//#region

function makeDir() {
    var dirName = '';
    var folderName = $('#txtFolderName').val();

    if (folderName != null && folderName.length > 0) {
        dirName = cDirectory + '/' + folderName;

        $.ajax({
            url: '/Handlers/StorageHandler.ashx',
            data: { command: "makedir", dirname: dirName },
            dataType: 'json',
            async: false,
            success: function (result) {
                var message = '';
                message += '<div class="nNote nSuccess hideit" style="width: 400px; margin: 0 10px 0 0">';
                message += '<p>Tạo mới thư mục <strong>' + dirName + '</strong>thành công.</p>';
                message += '</div>';
                message += '<div class="fix"></div>';
                
                viewDirectories(dirName, true); // refresh directories
                $('#messageFm').html(message); // message
            }
        });
    }

    $(".hideit").delay(2000).fadeOut(400);                    
    
    return false;
}

//#endregion

/***************************************
= Remove Dir
-------------------------------------- */
//#region
function removeDir() {
    console.log('Remove Dir: ' + cDirectory);

    var message = '';

    if (cDirectory != null && cDirectory.length > 0) {
        var isRemove = confirm("Bạn chắc chắn muốn xóa?");        
        
        if (isRemove == true) {
            $.ajax({
                url: '/Handlers/StorageHandler.ashx',
                data: { command: "removedir", dirname: cDirectory },
                dataType: 'json',
                async: false,
                success: function (result) {

                    message += '<div class="nNote nSuccess hideit" style="width: 400px; margin: 0 10px 0 0">';
                    message += '<p>Xóa thư mục <strong>' + cDirectory + '</strong>thành công.</p>';
                    message += '</div>';

                    var adminUserId = Base64.decode(AdminUserId);
                    viewDirectories('', 'files/' + adminUserId, true); // refresh directories
                    $('#messageFm').html(message); // message
                    $(".hideit").delay(2000).fadeOut(400);                    
                },
                error: function () {
                    message += '<div class="nNote nFailure hideits" style="width: 400px; margin: 0 10px 0 0">';
                    message += '<p>Xóa thư mục <strong>' + cDirectory + '</strong>không thành công. (Lưu ý xóa các thư mục con trước khi xóa thư mục cha)</p>';
                    message += '</div>';

                    $('#messageFm').html(message);
                    $(".hideit").delay(2000).fadeOut(400);                    
                }
            });    
        }
    }
        
    return false;
}
//#endregion

/***************************************
= Delete File
-------------------------------------- */

//#region

function deleteFile(obj) {
    var imgName = $(obj).attr('rel');
    
    if (imgName != null && imgName.length > 0) {
        var fileName = cDirectory + '/' + imgName;

        var isDelete = confirm("Bạn chắc chắn muốn xóa?");
        if (isDelete == true) {
            $.ajax({
                url: '/Handlers/StorageHandler.ashx',
                data: { command: "deletefile", filename: fileName },
                dataType: 'json',
                success: function () {
                    var message = '';
                    message += '<div class="nNote nSuccess hideit" style="width: 400px; margin: 0 10px 0 0">';
                    message += '<p>Xóa file <strong>' + cDirectory + '</strong>thành công.</p>';
                    message += '</div>';

                    viewDirectories('', cDirectory, true); // refresh
                    $('#messageFm').html(message); // message         

                    $(".hideit").delay(2000).fadeOut(400);
                },
                error: function (result) {
                    console.log('Error Delete File: ' + result);
                }
            });
        }
    }    
}

//#endregion

/***************************************
= Get File Info
-------------------------------------- */

//#region
/*
function getFileInfo(obj) {
        var imgName = $(obj).attr('rel');

    if (imgName != null && imgName.length > 0) {
        var fileName = cDirectory + '/' + imgName;

        alert('Get File Info: ' + fileName);
    }
}
*/
//#endregion

/***************************************
= Rename File
-------------------------------------- */

//#region
/*
function renameFile(oldFileName, newFileName) {
    $.ajax({
            url: '/Handlers/StorageHandler.ashx',
            data: { command: "renamefile", from: oldFileName, to: newFileName },
            dataType: 'json',
            success: function(result) {
                //Success            
                console.log(result);
                alert("Đổi tên file thành công!");
            },
            error: function(result) {
                alert("Lỗi đổi tên file.");
            }
        });
}
*/
//#endregion
